package com.jiuyou.storeController.store;

import com.jiuyou.storeController.common.StoreBaseController;
import com.ruoyi.common.constant.DicConstants;
import com.ruoyi.common.core.domain.entity.StoreUserRole;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.geoHash.GeoHash;
import com.ruoyi.framework.web.service.StoreUserTokenService;
import com.ruoyi.store.domain.StoreApply;
import com.ruoyi.store.service.IStoreApplyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author chengliang
 * @date 2021/11/17
 **/
@RestController
@RequestMapping("/store/storeApply")
public class StoreApplyStoreController  extends StoreBaseController {
    @Autowired
    private IStoreApplyService applyService;
    @Autowired
    private StoreUserTokenService tokenService;

    /**
     * 添加申请
     * @param apply
     * @return
     */
    @PutMapping
    public StoreApply apply(@RequestBody StoreApply apply){
        Long userId=getLoginStoreUserId();
        String serviceItem=apply.getServiceItem();
        if(StringUtils.isEmpty(serviceItem)){
            serviceItem="[]";
            apply.setServiceItem(serviceItem);
        }
        apply.setCreateBy(userId);
        GeoHash geoHash = new GeoHash(Double.parseDouble(apply.getLatitude()), Double.parseDouble(apply.getLatitude()));
        apply.setGeoCode(geoHash.getGeoHashBase32());
        apply.setApplyState(DicConstants.AUIT_STATE_IN.getCode());

        StoreApply applyQuery=new StoreApply();
        applyQuery.setCreateBy(userId);
        StoreApply storeApply= applyService.selectStoreApplyByCreateId(userId);
        if(null!=storeApply){
            //已经存在了
            return storeApply;
        }
        applyService.insertStoreApply(apply);
        return apply;
    }

    /**
     * 修改申请
     * @param apply
     * @return
     */
    @PostMapping
    public StoreApply update(@RequestBody StoreApply apply){
        apply.setUpdateBy(tokenService.getLoginStoreUserId());
        GeoHash geoHash = new GeoHash(Double.parseDouble(apply.getLatitude()), Double.parseDouble(apply.getLatitude()));
        apply.setGeoCode(geoHash.getGeoHashBase32());
        apply.setApplyState(DicConstants.AUIT_STATE_IN.getCode());
        applyService.reApply(apply);
        return apply;
    }

    /**
     * 获取门店申请
     * @return
     */
    @GetMapping
    public StoreApply getApply(){
        StoreUserRole storeUserRole= getStoreUserRole();
        if(null!=storeUserRole){
            Long storeId=storeUserRole.getStoreId();
            if(null!=storeId){
                return applyService.selectStoreApplyByStoreId(storeId);
            }
        }

        return applyService.selectStoreApplyByCreateId(tokenService.getLoginStoreUserId());
    }
}
